package com.liaoban.app.ui.login;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.liaoban.app.R;
import com.liaoban.app.api.type.request.SmsRequest;
import com.liaoban.app.api.type.request.UpdatePwdRequest;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.base.BaseToolbarActivity;
import com.liaoban.app.util.VerifyUtil;
import com.liaoban.app.widget.ClearEditText;
import com.liaoban.app.widget.MyTextWatcher;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ybc on 2018/7/6 0006.
 */
public class ForgetPwdActivity extends BaseToolbarActivity {
    @BindView(R.id.et_phone)
    ClearEditText etPhone;
    @BindView(R.id.et_ver_code)
    EditText etVerCode;
    @BindView(R.id.tv_ver_code)
    TextView tvVerCode;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;

    //最大倒计时长
    private static final long MAX_COUNT_TIME = 90;
    private Observable<Long> mObservableCountTime;
    private Consumer<Long> mConsumerCountTime;
    //用于主动取消订阅倒计时，或者退出当前页面。
    private Disposable mDisposable;

    @Override
    protected String getNewTitle() {
        return "找回密码";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_forget_pwd;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initListener();
        countDown();
    }

    private void initListener() {
        MyTextWatcher myTextWatcher = new MyTextWatcher(() -> {
            if (VerifyUtil.isMobileNO(etPhone.getText().toString().trim()) &&
                    etPwd.getText().toString().trim().length() >= 6 && etVerCode.getText().toString().trim().length() != 0) {
                tvSubmit.setEnabled(true);
                tvSubmit.setBackgroundResource(R.drawable.shape_yellow);
            } else {
                tvSubmit.setEnabled(false);
                tvSubmit.setBackgroundResource(R.drawable.shape_line);
            }
        });
        etPhone.addTextChangedListener(myTextWatcher);
        etVerCode.addTextChangedListener(myTextWatcher);
        etPwd.addTextChangedListener(myTextWatcher);
    }

    @OnClick({R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_submit:
                showRunningDialog();
                UpdatePwdRequest updatePwdRequest = new UpdatePwdRequest();
                String tel = etPhone.getText().toString().trim();
                updatePwdRequest.setUserTel(tel);
                updatePwdRequest.setPassword(etPwd.getText().toString().trim());
                updatePwdRequest.setCode(etVerCode.getText().toString().trim());
                startTask(CommonBiz.getInstance().updatePwd(updatePwdRequest), objectBaseResponse -> {
                    ToastHelper.show(ForgetPwdActivity.this, objectBaseResponse.msg);
                    if(objectBaseResponse.code == 1) {
                        finish();
                    }
                });
                break;
        }
    }

    /**
     * 倒计时
     */
    private void countDown() {
        mObservableCountTime = RxView.clicks(tvVerCode)
                //防止重复点击
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                //判断手机号否为空
                .flatMap(o -> {
                    String phone = etPhone.getText().toString().trim();
                    if (!VerifyUtil.isMobileNO(phone)) {
                        ToastHelper.show(this, "请输入正确的手机号码");
                        return Observable.empty();
                    }
                    return Observable.just(true);
                })
                //将点击事件转换成倒计时事件
                .flatMap(o -> {
                    //更新发送按钮的状态并初始化显现倒计时文字
                    RxView.enabled(tvVerCode).accept(false);
                    RxTextView.text(tvVerCode).accept(MAX_COUNT_TIME + " 秒");
                    tvVerCode.setBackgroundResource(R.drawable.shape_line);
                    //在实际操作中可以在此发送获取网络的请求,,续1s
                    SmsRequest smsRequest = new SmsRequest();
                    smsRequest.setUserTel(etPhone.getText().toString().trim());
                    startTask(CommonBiz.getInstance().duanxin(smsRequest), smsBaseResponse -> ToastHelper.show(ForgetPwdActivity.this, smsBaseResponse.msg));

                    return Observable.interval(1, TimeUnit.SECONDS, Schedulers.io())
                            .take(MAX_COUNT_TIME)
                            //将递增数字替换成递减的倒计时数字
                            .map(aLong -> MAX_COUNT_TIME - (aLong + 1));
                })
                //切换到 Android 的主线程。
                .observeOn(AndroidSchedulers.mainThread());

        mConsumerCountTime = aLong -> {
            //当倒计时为 0 时，还原 btn 按钮
            if (aLong == 0) {
                RxView.enabled(tvVerCode).accept(true);
                RxTextView.text(tvVerCode).accept(getString(R.string.get_ver_code));
                tvVerCode.setBackgroundResource(R.drawable.shape_yellow);
            } else {
                RxTextView.text(tvVerCode).accept(aLong + " 秒");
                tvVerCode.setBackgroundResource(R.drawable.shape_line);
            }
        };
        //订阅
        mDisposable = mObservableCountTime.subscribe(mConsumerCountTime);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }
}
